package com.blb.exam.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Cookie工具类
 */
public class CookieUtils {

    /**
     * 保存Cookie
     * @param key
     * @param value
     * @param maxAge
     */
    public static void saveCookie(HttpServletResponse response,String key, String value, int maxAge) throws IOException {
        //将对键和值进行编码
        key = URLEncoder.encode(key,"UTF-8");
        value = URLEncoder.encode(value, "UTF-8");
        //创建cookie
        Cookie cookie = new Cookie(key,value);
        //设置cookie
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        //添加cookie
        response.addCookie(cookie);
    }

    /**
     * 读取cookie值
     * @param request
     * @param key
     * @return
     */
    public static String readCookie(HttpServletRequest request,String key) throws IOException {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                //解码键和值
                String name = URLDecoder.decode(cookie.getName(), "UTF-8");
                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                if (key.equals(name)) {
                    return value;
                }
            }
        }
        return null;
    }

    /**
     * 删除Cookie
     * @param response
     * @param key
     */
    public static void removeCookie(HttpServletResponse response, String key) throws IOException {
        saveCookie(response,key,"",0);
    }
}
